<template>
  <div class="nmc-permissions">
    <div class="permission-header">
      <h3>NMC权限</h3>
    </div>
    
    <div class="nmc-table-container">
      <ElementTable
        ref="tableRef"
        :data="nmcList"
        :table-title="tableColumns"
        :show-pagination="false"
        row-key="id"
        empty-text="暂无NMC数据"
        @select-change="handleSelectionChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import ElementTable from '@/components/ElementTable/index.vue'

// Props
interface Props {
  modelValue: string[]
  nmcData?: any[]
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  nmcData: () => []
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: string[]]
}>()

// 响应式数据
const tableRef = ref()
const selectedNMCs = ref<any[]>([])
const nmcList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  {
    type: 'selection',
    width: '50'
  },
  {
    type: 'text',
    label: '名称',
    prop: 'name',
  },
  {
    type: 'text',
    label: 'IP',
    prop: 'ip',
  }
]

// 计算属性（暂时保留，可能后续会用到）
// const selectedNMCIds = computed(() => {
//   return selectedNMCs.value.map(nmc => nmc.id)
// })

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  console.log('选择变化:', selection)
  selectedNMCs.value = selection
  emitUpdate()
}

// 发出更新事件
const emitUpdate = () => {
  const result = selectedNMCs.value.map(nmc => nmc.id)
  emit('update:modelValue', result)
}

// 监听器
watch(
  () => props.modelValue,
  (newValue) => {
    // 检查当前选中的ID是否与传入的值一致，避免循环触发
    const currentSelectedIds = selectedNMCs.value.map(nmc => String(nmc.id)).sort()
    const newSelectedIds = (newValue || []).map(id => String(id)).sort()
    
    // 如果选择状态没有变化，不需要重新设置
    if (JSON.stringify(currentSelectedIds) === JSON.stringify(newSelectedIds)) {
      return
    }
    
    if (newValue && newValue.length > 0) {
      // 根据传入的值设置选中状态（支持字符串ID匹配）
      selectedNMCs.value = newValue.map(id => {
        const stringId = String(id) // 转换为字符串进行比较
        return nmcList.value.find(nmc => String(nmc.id) === stringId)
      }).filter(Boolean)
      
      // 更新表格选中状态
      nextTick(() => {
        if (tableRef.value) {
          tableRef.value.clearSelectionFun()
          selectedNMCs.value.forEach(nmc => {
            const row = nmcList.value.find(n => String(n.id) === String(nmc.id))
            if (row) {
              tableRef.value.toggleRowSelectionFun(row, true)
            }
          })
        }
      })
    } else {
      // 如果没有选中值，清空选择
      selectedNMCs.value = []
      nextTick(() => {
        if (tableRef.value) {
          tableRef.value.clearSelectionFun()
        }
      })
    }
  },
  { immediate: true }
)

// 监听传入的NMC数据
watch(
  () => props.nmcData,
  (newData) => {
    if (newData && newData.length > 0) {
      nmcList.value = newData
    } else {
      nmcList.value = []
    }
  },
  { immediate: true }
)


</script>

<style scoped>
.nmc-permissions {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.permission-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.permission-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.nmc-table-container {
  flex: 1;
  overflow: hidden;
}

:deep(.el-table) {
  height: 100%;
  min-height: 200px;
}

:deep(.el-table__header) {
  background-color: #f8f8f8;
}

:deep(.el-table__header th) {
  background-color: #f8f8f8;
  color: #333;
  font-weight: 600;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
